package cn.netty.example1;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

@ChannelHandler.Sharable
public class ServerHandler extends ChannelHandlerAdapter {


    /**
     * 业务处理逻辑
     * @param ctx 上下文对象,其中包含客户端建立的所有资源连接
     * @param msg 读取到的数据，默认是ByteBuf,是netty自定义的,是对Bytebuf的封装
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //读取缓冲中的数据
        ByteBuf buf = (ByteBuf) msg;
        //数组保存缓冲中的数据
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        String message = new String(bytes, "UTF-8");
        if ("exit".equals(message)){
            ctx.close();
            return;
        }

        String line =" return server message "+message;

        //写操作自动释放缓存
        ctx.writeAndFlush(Unpooled.copiedBuffer(line.getBytes("UTF-8")));
    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("ServerHandler exceptionCaught close");
        ctx.close();
    }
}
